package com.hsh.tools;

import com.hsh.tools.handler.BusinessException;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;

/**
 * 时间工具类
 *
 * @author huangsihai
 */
public class DateUtils2 extends org.apache.commons.lang3.time.DateUtils {

    private static final Logger logger = LoggerFactory.getLogger("!");

    private DateUtils2() {
    }

    public static final String YYYY = "yyyy";
    public static final String MM = "MM";
    public static final String DD = "dd";
    public static final String YYYY_MM = "yyyy-MM";
    public static final String YYYYMMDD = "yyyyMMdd";
    public static final String YY_MM_DD = "yyyy-MM";
    public static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
    public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
    public static final String YYYY_MM_DD = "yyyy-MM-dd";
    public static final String HH_MM_SS = "HH:mm:ss";
    private static final String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate() {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate() {
        return parseDateToStr(YYYY_MM_DD, getNowDate());
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd HH:mm:ss
     *
     * @return String
     */
    public static String getTime() {
        return parseDateToStr(YYYY_MM_DD_HH_MM_SS, getNowDate());
    }

    /**
     * 日期转换通用类
     *
     * @param format 日期格式
     * @param date   Date
     */
    public static String parseDateToStr(final String format, final Date date) {
        return new SimpleDateFormat(format).format(date);
    }

    /**
     * 获取年
     */
    public static String getYear() {
        return DateFormatUtils.format(getNowDate(), YYYY);
    }

    /**
     * @see #getMonth
     */
    public static String getMonth() {
        return getMonth(false);
    }

    /**
     * 获取月
     */
    public static String getMonth(boolean rejectZero) {
        if (rejectZero) {
            String day = DateFormatUtils.format(getNowDate(), MM);
            if (StringUtils.startsWith(day, StringUtils.ZERO)) {
                return day.replaceFirst(StringUtils.ZERO, StringUtils.NULLSTR);
            }
        }
        return DateFormatUtils.format(getNowDate(), MM);
    }

    /**
     * @see #getDay
     */
    public static String getDay() {
        return getDay(false);
    }

    /**
     * 获取日
     */
    public static String getDay(boolean rejectZero) {
        if (rejectZero) {
            String day = DateFormatUtils.format(getNowDate(), DD);
            if (StringUtils.startsWith(day, StringUtils.ZERO)) {
                return day.replaceFirst(StringUtils.ZERO, StringUtils.NULLSTR);
            }
        }
        return DateFormatUtils.format(getNowDate(), DD);
    }

    /**
     * Date 转时间戳
     *
     * @param date Date
     * @return 时间戳
     */
    public static Long dateConvertTimestamp(Date date) {
        if (date == null) return getNowDate().getTime();
        return date.getTime();
    }

    /**
     * Date 转时间戳
     *
     * @return 时间戳
     */
    public static Long dateConvertTimestamp() {
        return dateConvertTimestamp(getNowDate());
    }

    /**
     * @see #timestampConvertDate
     */
    public static Date timestampConvertDate(String timestamp) {
        return timestampConvertDate(Long.parseLong(timestamp));
    }

    /**
     * 获取指定日期中月份拥有的天数
     */
    public static int getDaysOfMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        if (date == null) {
            calendar.setTime(getNowDate());
        } else {
            calendar.setTime(date);
        }
        int month = Integer.parseInt(DateFormatUtils.format(calendar, MM));
        int amount = month - calendar.get(Calendar.MONTH) - 1;
        calendar.add(Calendar.MONTH, amount);
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    public static int getDaysOfMonth() {
        return getDaysOfMonth(getNowDate());
    }


    /**
     * 时间戳转 Date
     *
     * @param timestamp 十三位时间戳
     * @return Date
     */
    public static Date timestampConvertDate(Long timestamp) {
        try {
            return new Date(timestamp);
        } catch (Exception e) {
            logger.error("时间戳转换 date 失败！");
            throw new BusinessException("请传入有效时间戳！timestamp-> " + timestamp);
        }
    }

    /**
     * 增减参数，且截断 时分秒，只保留日期<br>
     * 2021-09-14 12:12:12 -> +1 -> 2021-09-15 00:00:00
     *
     * @param timestamp 时间戳
     * @param days      天数
     * @return Date
     */
    public static Date addDaysWithTruncate(Long timestamp, Integer days) {
        Date date = timestampConvertDate(timestamp);
        return addDaysWithTruncate(date, days);
    }

    /**
     * @see #addDaysWithTruncate
     */
    public static Date addDaysWithTruncate(String timestamp, Integer days) {
        return addDaysWithTruncate(Long.parseLong(timestamp), days);
    }

    /**
     * 增减参数，且截断 时分秒，只保留日期<br>
     * 2021-09-14 12:12:12 -> +1 -> 2021-09-15 00:00:00
     *
     * @param date 日期
     * @param days 天数
     * @return Date
     */
    public static Date addDaysWithTruncate(Date date, Integer days) {
        if (date == null || days == null) return date;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.add(Calendar.DAY_OF_MONTH, days);
        return calendar.getTime();
    }

    /**
     * 增减参数，且截断 时分秒，只保留日期【精准操作】<br>
     * 2021-09-14 12:12:12 -> +1 -> 2021-09-15 12:12:12
     *
     * @param date 日期
     * @param days 天数
     * @return Date
     */
    public static Date addDayWithTruncateAccurate(Date date, Integer days) {
        if (date == null || days == null) return date;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, days);
        return calendar.getTime();
    }

    /**
     * 获取指定时间的时间戳
     */
    public static Long getTimestamp(Date date) {
        return date.getTime();
    }

    /**
     * 获取指定时间的时间戳
     */
    public static Long getTimestamp() {
        return getTimestamp(getNowDate());
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static String dateTime() {
        Date now = new Date();
        return DateFormatUtils.format(now, YYYYMMDD);
    }

    /**
     * @param format 日期格式
     * @param ts     日期参数
     */
    public static Date dateTime(final String format, final String ts) {
        try {
            return new SimpleDateFormat(format).parse(ts);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(String str, String dateFormat) {
        if (str == null || str.trim().isEmpty()) {
            return null;
        }
        if (dateFormat == null || dateFormat.trim().isEmpty()) {
            dateFormat = YYYY_MM_DD_HH_MM_SS;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
//        if (dateFormat.equalsIgnoreCase("yyyy-MM-dd'T'HH:mm:ss")) {
//            sdf.setTimeZone(TimeZone.getTimeZone("UTC"));//时区定义并进行时间获取
//        }
        Date date = null;
        try {
            date = sdf.parse(str);
        } catch (ParseException e) {
            logger.error("DateUtils.parseDate({}, {}) ParseException", str, dateFormat);
        }
        return date;
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return parseDate(str.toString(), parsePatterns);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算两个时间差
     * nms：毫秒
     * ns：秒
     * nm：分钟
     * nh：小时
     * nd：天
     * 1day = 24hours
     * 1hours = 60minutes
     * 1minute = 60seconds
     * 1second = 1_000milliseconds
     */
    public static String getDatePoor(Date endDate, Date nowDate) {
        final long nms = 1, ns = 1_000 * nms, nm = 60 * ns, nh = 60 * nm, nd = 24 * nh;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 传入时间是否大于当前时间
     *
     * @param beforeDate 参数时间
     * @param afterDate  当前时间
     * @return bool
     */
    public static boolean checkGtCurrentDateTime(Date beforeDate, Date afterDate) {
        return beforeDate.getTime() > afterDate.getTime();
    }

    /**
     * 传入时间是否大于当前时间
     *
     * @param beforeDate 参数时间
     * @return bool
     */
    public static boolean checkGtCurrentDateTime(Date beforeDate) {
        return checkGtCurrentDateTime(beforeDate, getNowDate());
    }

    // ***************************JDK8 日期和 Date 互转******************************
    public static Date asDate(LocalDate localDate) {
        return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
    }

    public static Date asDate(LocalDateTime localDateTime) {
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }

    public static LocalDate asLocalDate(Date date) {
        return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
    }

    public static LocalDateTime asLocalDateTime(Date date) {
        return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
    }
}
